<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="问题编号">
          <el-input
            v-model="searchParam.qualityProblemCode"
            placeholder="请输入问题编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item label="产品名称">
          <el-input
            v-model="searchParam.productProjectName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item label="责任部门">
          <el-tree-select
            placeholder="请选择类型"
            v-model="searchParam.departmentId"
            :data="organizationList"
            :render-after-expand="false"
            :check-strictly="true"
            node-key="id"
            :props="{
              label: 'organizationCode',
              value: 'id',
              children: 'nodes',
            }"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="问题状态">
          <el-select
            v-model="searchParam.releaseState"
            placeholder="请选择问题状态"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('releaseStateOne')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="质量问题">
          <el-select
            v-model="searchParam.problemTypeCode"
            placeholder="请选择质量问题"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('ExceptionType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :selectable="selected"
          width="55"
          align="center"
        />
        <el-table-column
          label="状态"
          prop="releaseState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              dictionaryStore.filterDictName(
                "releaseStateOne",
                scope.row.releaseState
              )
            }}
          </template>
        </el-table-column>

        <el-table-column
          label="质量问题"
          prop="problemTypeCode"
          min-width="180"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              dictionaryStore.filterDictName(
                "ExceptionType",
                scope.row.problemTypeCode
              )
            }}
          </template>
        </el-table-column>

        <el-table-column
          label="问题编号"
          prop="qualityProblemCode"
          min-width="180"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column label="问题描述" align="center">
          <el-table-column
            label="生产线/过程"
            prop="lineProcessName"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="产品/项目名"
            prop="productProjectName"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="型号/编号"
            prop="materialProcessFigure"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="失效模式"
            prop="failureModeContent"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="发生地点"
            prop="occurrenceLocation"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="产品/过程状态"
            prop="productProcessContent"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
        </el-table-column>

        <el-table-column
          label="失效后果及影响"
          prop="consequenceInfluence"
          min-width="140"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="问题发生频度"
          prop="problemFrequency"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          label="责任部门编号"
          prop="departmentCode"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="责任部门名称"
          prop="departmentName"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="370">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              :disabled="scope.row.releaseState != 0"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.releaseState != '0'"
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.releaseState != '0'"
              @click="releaseItem(scope.row)"
              ><i-ep-circleCheck />发布</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="
                scope.row.releaseState != '1' ||
                scope.row.problemApproachType != 0
              "
              @click="openDialog2(scope.row)"
              ><i-ep-switch />发布审批</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <q8dqualichecklist-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <q8dreleaseItem-edit
      :visible="addDialog1.visible"
      :title="addDialog1.title"
      :data="addDialog1.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog1.readvisible"
      @change-visible="changeVisible1"
    />
    <publishApproval
      :visible="addDialog2.visible"
      :title="addDialog2.title"
      :data="addDialog2.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog2.readvisible"
      @change-visible2="changeVisible2"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
// import html2pdf from "./components/PDF.js";
import dayjs from "dayjs";
const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "QMSQ8DQUALITYCHECKLIST",
  inheritAttrs: false,
});

function PDFprit() {
  const table = document.getElementById("table");
  // html2pdf(table, {
  //   background: "#fff",
  //   minimumUnit: "tr",
  //   orientation: "l",
  // });
  // html2pdf("table", "对账单", dayjs(new Date()).format("YYYY-mm-dd"));
}

// 请求参数
const requestApi = "/qms/q8dqualityproblem/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  qualityProblemCode: "",
  productProjectName: "",
  departmentId: "",
  releaseState: "",
  problemTypeCode: "",
};

const deleteParam = {
  api: "/qms/q8dqualityproblem/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  console.log(tableData.value);
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/q8dqualityproblem/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开质量问题信息表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改质量问题信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增质量问题信息";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开质量问题信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "质量问题清单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  addDialog1.visible = value;
  addDialog2.visible = value;
  if (!value) {
    addDialog.data = {};
    addDialog1.data = {};
    addDialog2.data = {};
  }
}

function getproblemTime(data: any) {
  if (data) {
    searchParam.value.problemTimeStart = data[0];
    searchParam.value.problemTimeEnd = data[1];
  } else {
    searchParam.value.problemTimeStart = "";
    searchParam.value.problemTimeEnd = "";
  }
}
function getapprovalTime(data: any) {
  if (data) {
    searchParam.value.approvalTimeStart = data[0];
    searchParam.value.approvalTimeEnd = data[1];
  } else {
    searchParam.value.approvalTimeStart = "";
    searchParam.value.approvalTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/qms/q8dqualityproblem/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功");
      search();
    });
  });
}

// 责任部门

const organizationList = ref([]);
const getOrganizationList = async () => {
  let res = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 4 },
  }).finally(() => {});
  organizationList.value = res.data;
};

// 发布按钮
const addDialog1 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开质量问题信息表单弹窗 详情 */
function changeVisible1(value: boolean) {
  addDialog1.visible = value;
  if (!value) {
    addDialog1.data = {};
  }
}

const releaseItem = (row: any) => {
  if (row) {
    addDialog1.title = "问题发布";
    addDialog1.data = row;
    addDialog1.visible = true;
  } else {
    addDialog1.title = "问题发布";
    addDialog1.visible = true;
  }
};

// 发布按钮
const addDialog2 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开质量问题信息表单弹窗 详情 */
function changeVisible2(value: boolean) {
  addDialog2.visible = value;
  if (!value) {
    addDialog2.data = {};
  }
}

// 查询详情
async function getMeasureList(id: string) {
  request({
    url: `/qms/q8dqualityproblem/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog2.data = data.data;
      addDialog2.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开质量问题信息表单弹窗 */
function openDialog2(roleObj?: Object) {
  if (roleObj) {
    addDialog2.title = "纠正预防措施";
    // getMeasureList(roleObj.id);
    addDialog2.data = roleObj;
    addDialog2.visible = true;
  } else {
    addDialog2.title = "纠正预防措施";
    addDialog2.visible = true;
  }
  addDialog2.readvisible = false;
}
/** 打开质量问题信息表单弹窗 详情 */
function changeVisible3(value: boolean) {
  addDialog2.visible = value;
  if (!value) {
    addDialog2.data = {};
  }
}

// 停用过滤
const selected = (row) => {
  if (row.releaseState != 0) {
    return false; //不可勾选
  } else {
    return true; //可勾选
  }
};

onMounted(() => {
  getOrganizationList();
});
</script>
